//var HOST = 'http://working-time.appspot.com'; var open_prefix = ''; /*remote*/
var HOST = 'http://localhost:8080'; var open_prefix = HOST; /*local*/


var cache = {}

/* cpu functions */
var cpu = {
    /**
     * function returns user's timezone offset
     **/
    get_tz_offset: function() {
        var x = new Date()
        var hours = -x.getTimezoneOffset()/60;
        var sign = (hours < 0) ? '-' : '';
        hours = Math.abs(hours);
        var minutes = x.getTimezoneOffset()%60;
        return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes);
    },

    tic: function() {
      if (cache && cache.response && cache.response.data && cache.response.data.status && cache.response.data.time) {
        var now = new Date();
        var now_timestamp = now.getTime();
        var tz_offest = now.getTimezoneOffset()*60*1000;
        var timedelta = (now_timestamp - (cache.response.data.time*1000 + tz_offest))/1000/3600;
        timedelta = (Math.floor(timedelta*10)/10).toFixed(1);
        chrome.browserAction.setBadgeText({text: timedelta.toString()});
      } else {
        cpu.delete_timer();
      }
    },

    create_timer: function() {
      if (typeof timer != 'undefined') { console.log(0); cpu.delete_timer(); }
      timer = setInterval(cpu.tic, 1000*60);
      cpu.tic();
    },
    delete_timer: function() {
      clearInterval(timer);
      delete timer;
    }
}

function set_icon_status(type) {
    var options = {
        'authorized': {'icon': 'wt-19', 'title': 'connected', 'popup': 'popup.html' },
        'not authorized': {'icon' : 'wt-19.grey', 'title': 'not connected', 'popup': '' }
    };

    chrome.browserAction.setIcon({ path:options[type]['icon'] + ".png" });
    chrome.browserAction.setTitle({ title: options[type]['title'] });
    chrome.browserAction.setPopup({ popup:options[type]['popup'] });
}

function get_user(login) {
    $.get(HOST+'/worker/get',
    {'auth_token': localStorage['auth_token']},
    function(data){
        if (typeof data.success != 'undefined') {
            //save user status
            set_icon_status('authorized');
            //set user cache
            cache.response = data;
        } else {
            //go to login page
            if (login)
                chrome.tabs.create({'url': open_prefix + data.open});
        }
    }, 'json');
}


/*button handler*/
function main_click() {
    get_user('login');
}
chrome.browserAction.onClicked.addListener(main_click);


/*listener *** contentscript and popup */
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
    if (request.contentscript_token) {
        localStorage['auth_token'] = request.contentscript_token;
        if (request.contentscript_token!='logout') {
            get_user();
        } else {
            set_icon_status('not authorized');
        }
    }

    if (request.popup_get_cache){
        if (typeof cache.response != 'undefined') {
            sendResponse(cache.response);
        } else {
            sendResponse(false);
        }
    }

    if (request.popup_get){
        $.get(HOST+'/worker/get',
        {'auth_token': localStorage['auth_token']},
        function(data){
            if (data.open) {
                chrome.tabs.create({'url': open_prefix + data.open});
                return;
            }
            cache.response = data;
            cpu.create_timer();
            sendResponse(data);
    }, 'json');
}

if (request.popup_go_work){
    $.get(HOST+'/worker/go-work',
    {'auth_token': localStorage['auth_token'], 'tz_offset':cpu.get_tz_offset()},
    function(data){
            if (data.open) {
                chrome.tabs.create({'url': open_prefix + data.open});
                return;
            }
            cache.response = data;
            cpu.create_timer();
            sendResponse(data);
    }, 'json');
}

if (request.popup_go_relax){
    $.get(HOST+'/worker/go-relax',
    {'auth_token': localStorage['auth_token'], 'tz_offset':cpu.get_tz_offset()},
    function(data){
            if (data.open) {
                chrome.tabs.create({'url': open_prefix + data.open});
                return;
            }
            cache.response = data;
            cpu.delete_timer();
            chrome.browserAction.setBadgeText({text: ''});
            sendResponse(data);
    }, 'json');
}

if (request.popup_open_spot) {
    chrome.tabs.create({'url': HOST+'/?kick=off'});
}

return true;
});






/*main fnc*/
function main() {
get_user();
cpu.create_timer();
}

main();


